import { defineStore } from 'pinia'
import $ajaxGrid from '../api/to8082.js'
import $ajaxFeedback from '../api/to8083.js'
import $ajaxAqi from '../api/to8084.js'
import moment from 'moment'
import router from '@/router/index'

import { alertMsg } from '@/utils/msg.js'

export const Gridors = defineStore('gridors', {
  state: () => ({
    /** @type { value:number,label:String,children:list} */
    gid: localStorage.getItem('gid') === null ? -1 : localStorage.getItem('gid'),
    his: [],
    list: [],
    dialogShow: false,
    curListRow: -1,
    curListInfo: '',
    curHisRow: -1,
    curHisInfo: '',
    rules: [
      { required: true, message: '此项不能为空' },
      { type: 'number', message: '填写内容必须是数值' }
    ],
    feedbackForm: {
      so2value: '',
      covalue: '',
      spmvalue: ''
    },
    msg: '',
    curRes: '',
    feedbackHis: []
  }),
  getters: {
    filterGridors(state) {
      this.loadData()
      return state.cascader
    },
    getData(state) {
      return state.list
    }
  },
  // 也可以这样定义
  // state: () => ({ count: 0 })
  actions: {
    loadData() {
      this.loadList()
    },
    goback() {
      router.push({ name: 'flist' })
    },
    goback2() {
      router.push({ name: 'feedback' })
    },

    todo(id) {
      this.curListRow = id
      this.curListInfo = this.list.find((item) => item.id === id)
      console.log(this.curListInfo)
    },
    async loadList() {
      const path = '/feedback/g/todo/' + this.gid

      const res = await $ajaxFeedback.get(path)

      if (res.code === 200) this.list = res.data

      console.log(this.list)
    },
    async loadHis() {
      const path = '/feedback/g/his/' + this.gid
      const res = await $ajaxFeedback.get(path)
      if (res.code === 200) this.feedbackHis = res.data
      console.log(this.feedbackHis)
    },

    cancel() {},

    async commit() {
      console.log(this.feedbackForm)
      const path = '/feedback/g/commit/' + this.curListRow
      console.log(path)
      const res = await $ajaxFeedback.post(path, this.feedbackForm)
      if (res.code === 200) {
        this.curRes = res.data
        console.log(this.curRes.aqilevel + '级 AQI实际指数')
        alertMsg(res.code, res.msg)

        this.list.splice(
          this.list.findIndex((item) => item.id === this.curListRow),
          1
        )
      }
    },
    clearRes() {
      this.curRes = ''
      this.feedbackForm = {
        so2value: '',
        covalue: '',
        spmvalue: ''
      }
    }
  }
})
